<?php
	session_start();
	$link = mysqli_connect('127.0.0.1','root','','blog');
	mysqli_set_charset($link,'utf8');

	if(isset($_POST['user'])&&isset($_POST['pass1'])&&isset($_POST['pass2'])&&isset($_POST['phone'])&&isset($_POST['email'])&&isset($_POST['cap'])){
		
		$code=$_SESSION['str'];
		$code=mb_convert_encoding($code,'UTF-8','GBK');
		
		$error = "";
		$user = trim($_POST['user'],"\t\n\r\0\x0B");
		// echo $user;
		if ($code!=$_POST['cap']) {
			$error = "验证码填写错误！";
			$code = "111";
		}elseif (!$_POST['user']) {
			$error = "请填写用户名！";
			$code="001";
		}elseif (!(preg_match('/[a-z]+/', $user)&&preg_match('/[A-Z]+/', $user)&&preg_match('/[0-9]+/', $user))){
			$error = "用户名格式不对";
			$code="002";
		}elseif (!$_POST['pass1']) {
			$error = "请填写密码！";
			$code="003";
		}elseif (strlen($_POST['pass1'])<6||strlen($_POST['pass1'])>20) {
			$error = "密码位数在6-20之间";
			$code = "00311";
		}elseif (!$_POST['pass2']) {
			$error = "请确认密码！";
			$code="004";
		}elseif($_POST['pass1']!=$_POST['pass2']){
			$error = "两次密码不一致";
			$code="005";
		}elseif (!$_POST['phone']) {
			$error = "请填写手机号码！";
			$code="006";
		}elseif (!preg_match('/13[0-9]{8}|15[0-9]{8}|18[0-9]{8}/', $_POST['phone'])) {
			$error = "手机号码格式不对！";
			$code="007";	
		}elseif (!$_POST['email']) {
			$error = "请填写邮箱！";
			$code="008";
		}elseif (!preg_match('/^[_.0-9a-z-]+@(?:[0-9a-z][0-9a-z-]+.)+[a-z]{2,3}$/', $_POST['email'])) {
			$error = "邮箱格式不对！";
			$code="009";
		}

		if($error){
			$_SESSION['error']=$error;
			$_SESSION['code']=$code;
			$_SESSION['user']=$_POST['user'];
			header("location:login.php");
			exit;
		}
		$user = addslashes($_POST['user']);
		$pass1 = addslashes($_POST['pass1']);
		$phone = addslashes($_POST['phone']);
		$email = addslashes($_POST['email']);

		$sql="SELECT * FROM user WHERE user='{$user}' AND phone='{$phone}'";
		$res=mysqli_query($link,$sql);
		$row=mysqli_fetch_assoc($res);
		if($row){
			$error = "用户名{$user}已使用";
			$_SESSION['error']=$error;
			$_SESSION['code']='010';
			header("location:login.php");
			exit;
		}

		$sql="INSERT INTO user (user,password,phone,email) VALUES ('{$user}','{$pass1}','{$phone}','{$email}');";
		echo $sql;
		$r=mysqli_query($link,$sql);
		echo $r;
		if($r){
			echo  "注册成功";
			header("location:register.html");
		}else{
			$error = "注册失败";
			$_SESSION['error']=$error;
			$_SESSION['code']='011';
			header("location:login.php");
			exit;
		}
	}

?>